# Tem Module Class
# Tem version: 0.3

class Modules
	def initialize(command_handler)
	# Here we want to initially define the module class variables and load up modules.
		@command_handler = command_handler
		$Loaded_Modules = {} # Define the dictionary to keep the loaded module list.
		$Module_Includes.each do |module_include|
			# This loop loads up each module file and allows them to hook triggers.
			begin
				load module_include
				prnt "[Modules] Loaded #{module_include} successfully!"
			rescue
				prnt "[Modules] ERROR: Failed to load #{module_include}!"
			end
		end
	end


	def parse_to_module(trigger, parameters, subject, authed)
	# This function takes the command trigger and sends required information to 
	# any modules that hook into the $Loaded_Modules dictionary.
		$Loaded_Modules.keys.each do |trigger_hook|
			# This loop processes the trigger hooks for modules.
			if trigger_hook == trigger
				class_call = $Loaded_Modules[trigger]+".new(@command_handler, trigger, subject, parameters, authed)"
				eval(class_call)
			end
		end
	end

	def dynamic_load(module_file, subject = nil)
	# A routine for dynamic (runtime) module loading.
	# NOTE: Use this to also reload modules when testing etc as it rehashes the included code.
	# Ruby does not support an efficient method of unloading yet.
			begin
				load module_file
				if subject == nil
					prnt "[Modules] Loaded #{module_file} successfully!"
				else
					@command_handler.privmsg(subject, "[Modules] Loaded #{module_file} successfully!")
				end
			rescue
				if subject == nil
					prnt "[Modules] ERROR: Failed to load #{module_file}!"
				else
					@command_handler.privmsg(subject, "[Modules] ERROR: Failed to load #{module_file}!")
				end
			end
	end
end
